//
//  AWHomePictureView.swift
//  WeiBo
//
//  Created by AaronWei on 2017/6/10.
//  Copyright © 2017年 AaronWei. All rights reserved.
//

import UIKit
import SDWebImage

private let ItemMargin: CGFloat = 5

private let ItemWidth: CGFloat = (ScreenWidth - 2 * HomeCellMargin - 2 * ItemMargin) / 3

class AWHomePictureView: UICollectionView {
    
    var picUrls: [AWHomePicInfoModel]? {
        
        didSet {
            
            guard let currentPicUrls = picUrls else { return }
            
            if currentPicUrls.count > 0 {
                
                countPictureViewSize(count: currentPicUrls.count)
                
            }
            
            reloadData()
            
        }
        
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
        
        flowLayout.minimumLineSpacing = ItemMargin
        
        flowLayout.minimumInteritemSpacing = ItemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
        
    }
    
    private func setupUI() {
        
        dataSource = self
        
        register(AWHomePictureViewCell.self, forCellWithReuseIdentifier: HomePictureViewIdentifier)
        
    }
    
    private func countPictureViewSize(count: Int) {
        
        //  判断是否是单张图片
        if count == 1 {
            //  单张图片的地址
            let imageUrl = picUrls!.first!.thumbnail_pic!
            //  单张图片
            if let localImage = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: imageUrl) {
                //  我们只是默认处理单张图片，正常来说这个大小应该由服务端给我们提供
                //  获取大小
                var imageSize = localImage.size
                //  图片过窄
                if imageSize.width < 80 {
                    let currentWidth: CGFloat = 80
                    //  计算高度
                    var currentheight = currentWidth / imageSize.width * imageSize.height
                    //  过高
                    if currentheight > 150 {
                        currentheight = 150
                    }
                    //  计算好的大小
                    imageSize = CGSize(width: currentWidth, height: currentheight)
                }
                
                //  找到单张图片
                self.snp.updateConstraints({ (make) in
                    //  把单张图片的大小作为配图的大小
                    make.size.equalTo(imageSize).priority(.high)
                })
                
                // 修改配图item的大小
                let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
                flowLayout.itemSize = imageSize
                
                return
            }
            
        }
        
        //  列数计算
        let cols = count > 3 ? 3 : count
        //  行数计算
        let rows = (count - 1) / 3 + 1
        //  计算配图宽度
        let pictureViewWidth = CGFloat(cols) * ItemWidth + CGFloat(cols - 1) * ItemMargin
        //  计算配图高度
        let pictureViewHeight =  CGFloat(rows) * ItemWidth + CGFloat(rows - 1) * ItemMargin
        //  当前配图大小
        let pictureViewSize = CGSize(width: pictureViewWidth, height: pictureViewHeight)
        //  更新配图大小
        self.snp.updateConstraints { (make) in
            
            make.size.equalTo(pictureViewSize).priority(.high)
            
        }
        //  不是单张图片，需要设置成为计算好的配图item的大小
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
    
    }
    
}

extension AWHomePictureView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return picUrls?.count ?? 0
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomePictureViewIdentifier, for: indexPath) as! AWHomePictureViewCell
        
        cell.picInfo = picUrls?[indexPath.item]
        
        return cell
        
    }
    
}

class AWHomePictureViewCell: UICollectionViewCell {
    
    fileprivate lazy var pictureImageView: UIImageView = {
        
        let imageView = UIImageView(image: #imageLiteral(resourceName: "timeline_image_placeholder"))
        
        imageView.contentMode = .scaleAspectFill
        
        imageView.clipsToBounds = true
        
        return imageView
        
    }()
    
    var picInfo: AWHomePicInfoModel? {
        
        didSet {
            
            if let picUrl = picInfo?.thumbnail_pic {
                
                pictureImageView.sd_setImage(with: URL(string: picUrl), placeholderImage: #imageLiteral(resourceName: "timeline_image_placeholder"))
                
            }
            
        }
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
        
    }
    
    private func setupUI() {
        
        contentView.addSubview(pictureImageView)
        
        pictureImageView.snp.makeConstraints { (make) in
            
            make.edges.equalTo(contentView)
            
        }
        
    }
    
}
